﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.UnitGrid;
using SC.GridManage.Domain.Models;

namespace SC.GridManage.API.Write.Application.Handler.UnitGrid
{
    public class CreateUnitGridHandler : IRequestHandler<CreateUnitGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UnitGridModel> unitgridRepo;
        private readonly IMapper mapper;

        public CreateUnitGridHandler(IBaseRepository<UnitGridModel> unitgridRepo, IMapper mapper)
        {
            this.unitgridRepo = unitgridRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateUnitGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            //查询数据库中是否已有GridNo 网格编号
            var count = unitgridRepo.QueryAsync(x => x.GridNo == request.GridNo).Result.Count();
            if (count >= 1)
            {
                result.Data = count;
                result.Msg = "单元网格已经存在.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Error;
                return Task.FromResult(result);
            }

            var model = mapper.Map<UnitGridModel>(request);

            int r = unitgridRepo.CreateAsync(model).Result;
            if (r > 0)
            {
                result.Data = r;
                result.Msg = "单元网格创建成功.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
            }
            else {
                result.Data = r;
                result.Msg = "单元网格创建失败.";
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
